/* $Id:contractors.cc $ */
/*
   Copyright (C) 2007 by Jurjen Stellingwerff <jurjen@stwerff.xs4all.nl>
   Part of the Moros Project http://moros.sourceforge.net/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 3.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#define DEBUG_ROUTINE "contractors"

#include <sstream>
#include <fstream>
#include "../general/util.h"
#include "../general/log.h"
#include "../general/channel.h"
#include "contractors.h"
#include "person.h"
#include "../general/general.h"

contractors::contractors() {
    person=0;
    type=-1;
}

// Field : person

class person& contractors::getPerson() const { if (person==0) throw nullpointer(); return *person; }
void contractors::setPerson(class person &v) { person=&v; }

// Field : type

const string contractorsType[]={"originator","blesser","actor"};
const int contractors::getType() const { return type; }
const string contractors::showType() const {
    if (type<0) return "";
    else return contractorsType[type];
}
void contractors::setType(const int  v) {
    if (v<0 || (unsigned int)v >= sizeof contractorsType/sizeof contractorsType[0]) type=-1;
    else type=v;
}
void contractors::setType(const string v) {
    type=-1;
    loopArray(contractorsType, tp, string) {
        if (v==*tp) {type=tp_i; break; }
    }
    if (type==-1) dbg_state("Enumerate contractors.type %s has unknown '%s'", getPerson().getName().c_str(), v.c_str());
}

void contractors::save(class channel &ch) {
    ch.write("contractors", "");
    ch.write("p", getPerson().getName());
    ch.write("t", getType());
}

void contractors::load(class channel &ch) {
    if (ch.key=="p" || ch.key=="person") {
        if (!person_repo.isPerson(ch.value)) {
            dbg_state("link unknown person %s", ch.value.c_str());
            class person rec;
            rec.setName(ch.value);
            person_repo.setPerson(rec);
        }
        setPerson(person_repo.getPerson(ch.value));
        ch.next();
    }
    if (ch.key=="t" || ch.key=="type") { setType(ch.value); ch.next(); }
}

void contractors::xml(ofstream &f, int l, int r) {
    f << ncpy(l, "  ") << "<contractors type=\"" << showType() <<
    "\">" << endl;
    if (r<2) try {
        getPerson().xml(f,l+1,r+1);
    } catch (nullpointer n) {}
    f << ncpy(l, "  ") << "</contractors>" << endl;
}
